import Vue from 'vue'
import Native from '@/service/native'
import store from '@/service/store'
import router from './index'

router.beforeEach(async (to, from, next) => {
  /**
   * 处理跳转
   */
  if (/\/http/.test(to.path)) { // to  的地址为http地址则做重定向
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
    return
  }

  // 如果不是本地模拟 则获取扩展参数
  if (process.env.NODE_ENV !== 'development') {
    try {
      let extra = await Native.apiCall('MideaCommon', 'getExtra', [])
      let scanExtra = await Native.apiCall('MideaBarcode', 'getScanExtra', [])
      console.log('extra:', extra)
      console.log('scanExtra:', scanExtra)
      if (extra && extra.extra) {
        extra = extra.extra
      }
      if (extra && extra.showWidgetKey) {
        extra = JSON.parse(extra.showWidgetKey)
      }
      if (extra && extra.action) {
        store.commit('extraStore/updateExtra', extra)
        next({
          name: extra.action,
          params: extra
        })
      } else if (scanExtra !== 'null' && scanExtra !== null) {
        // 示例二维码内容 {"target":"com.meicloud.hnvue","action":"scan_open_h5","param":{ "action" : "otherDemo","a": 1}}
        scanExtra = JSON.parse(scanExtra)
        if (scanExtra.param) {
          scanExtra = scanExtra.param
        }
        store.commit('extraStore/updateExtra', scanExtra)
        if (scanExtra.action) {
          next({
            name: scanExtra.action,
            params: scanExtra
          })
        } else {
          next()
        }
      } else {
        next()
      }
    } catch (error) {
      console.log('router error:', error);
    }
  } else {
    next()
  }
})

router.afterEach(function (to) {
  Vue.$mxLoading.hide()
})

export default router